package a11_Network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Author quan
 * @Description 客户端
 * @Date 2023/5/30 11:09
 */
public class TCPEchoClient {
    //定义一个用于客户端的Socket对象
    private Socket clientSocket;

    /**
     * 初始化客户端Socket
     * @param serverIP 服务器IP地址
     * @param serverPort 服务器端口号
     * @throws IOException
     */
    public TCPEchoClient(String serverIP,int serverPort) throws IOException {
        this.clientSocket = new Socket(serverIP,serverPort);
    }

    /**
     * 启动客户端
     */
    public void start() throws IOException {
        System.out.println("客户端已经启动");
        //inputStream 读取数据,outputStream写入数据
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
           //循环处理用户的输入
            while (true){
                System.out.println("->");
                //1、接收用户的输入内容
                Scanner sc = new Scanner(System.in);
                String request = sc.nextLine();
                //2、发送用户请求
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                //3、强制刷新缓冲区
                printWriter.flush();
                //4、接收服务器的响应
                Scanner respondScanner = new Scanner(inputStream);
                //5、获取响应数据
                String respond = respondScanner.nextLine();
                //打印响应数据
                System.out.println("接收到服务器的响应："+respond);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭
            clientSocket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient client = new TCPEchoClient("127.0.0.1",9999);
        client.start();
    }
}
